// 统计分析报表功能实现

// 使用全局函数，不再使用ES模块导入

// 报表数据状态
const reportsState = {
    // 图表对象引用
    revenueChart: null,
    industryChart: null,
    performanceChart: null,
    activityChart: null,
    // 时间范围
    timeRange: 'quarter', // month, quarter, year
    // 部门筛选
    departmentFilter: 'all',
    // 产品筛选
    productFilter: 'all'
};

// 初始化报表页面
function initReports() {
    // 监听路由变更事件
    window.addEventListener('routeChanged', (e) => {
        if (e.detail.route === 'reports') {
            // 延迟一点时间初始化图表，确保DOM已经渲染
            setTimeout(() => {
                initReportCharts();
                initReportFilters();
                initReportExport();
            }, 100);
        }
    });
    
    // 初始加载时，如果当前是报表页面，则初始化
    if (document.getElementById('reports').classList.contains('active')) {
        setTimeout(() => {
            initReportCharts();
            initReportFilters();
            initReportExport();
        }, 100);
    }
}

// 初始化报表图表
function initReportCharts() {
    // 初始化收入趋势图
    initRevenueChart();
    
    // 初始化行业分布图
    initIndustryChart();
    
    // 初始化销售业绩图
    initPerformanceChart();
    
    // 初始化活动统计图表
    initActivityChart();
}

// 初始化收入趋势图
function initRevenueChart() {
    const ctx = document.getElementById('revenueChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (reportsState.revenueChart) {
        reportsState.revenueChart.destroy();
    }
    
    // 根据时间范围获取数据
    let labels, data, data2;
    
    switch (reportsState.timeRange) {
        case 'month':
            labels = ['第1周', '第2周', '第3周', '第4周'];
            data = [450000, 520000, 610000, 580000]; // 实际收入
            data2 = [420000, 480000, 550000, 540000]; // 预期收入
            break;
        case 'year':
            labels = ['Q1', 'Q2', 'Q3', 'Q4'];
            data = [5200000, 5800000, 6500000, 7200000];
            data2 = [4800000, 5300000, 6000000, 6800000];
            break;
        case 'quarter':
        default:
            labels = ['1月', '2月', '3月'];
            data = [1500000, 1800000, 1900000];
            data2 = [1400000, 1600000, 1750000];
            break;
    }
    
    // 创建图表
    reportsState.revenueChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: labels,
            datasets: [
                {
                    label: '实际收入',
                    data: data,
                    backgroundColor: 'rgba(52, 152, 219, 0.8)',
                    borderColor: 'rgba(52, 152, 219, 1)',
                    borderWidth: 1
                },
                {
                    label: '预期收入',
                    data: data2,
                    backgroundColor: 'rgba(231, 76, 60, 0.3)',
                    borderColor: 'rgba(231, 76, 60, 0.8)',
                    borderWidth: 1,
                    borderDash: [5, 5]
                }
            ]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    callbacks: {
                        label: function(context) {
                            const label = context.dataset.label || '';
                            const value = context.parsed.y;
                            return `${label}: ${formatCurrency(value)}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    grid: {
                        display: false
                    }
                },
                y: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return formatCurrency(value);
                        }
                    }
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 初始化行业分布图
function initIndustryChart() {
    const ctx = document.getElementById('industryChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (reportsState.industryChart) {
        reportsState.industryChart.destroy();
    }
    
    // 行业数据
    const industries = ['互联网', '电子商务', '金融', '制造业', '房地产', '医疗健康', '教育培训', '其他'];
    const data = [25, 18, 15, 12, 10, 8, 7, 5]; // 百分比
    
    // 颜色数组
    const colors = [
        'rgba(52, 152, 219, 0.8)',
        'rgba(155, 89, 182, 0.8)',
        'rgba(46, 204, 113, 0.8)',
        'rgba(243, 156, 18, 0.8)',
        'rgba(231, 76, 60, 0.8)',
        'rgba(26, 188, 156, 0.8)',
        'rgba(149, 165, 166, 0.8)',
        'rgba(127, 140, 141, 0.8)'
    ];
    
    // 创建环形图
    reportsState.industryChart = new Chart(ctx, {
        type: 'doughnut',
        data: {
            labels: industries,
            datasets: [{
                data: data,
                backgroundColor: colors,
                borderColor: '#fff',
                borderWidth: 2
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'right',
                    labels: {
                        padding: 20,
                        usePointStyle: true,
                        boxWidth: 6,
                        generateLabels: function(chart) {
                            const data = chart.data;
                            if (data.labels.length && data.datasets.length) {
                                return data.labels.map((label, i) => {
                                    const value = data.datasets[0].data[i];
                                    return {
                                        text: `${label}: ${value}%`,
                                        fillStyle: data.datasets[0].backgroundColor[i],
                                        strokeStyle: data.datasets[0].borderColor[i],
                                        lineWidth: data.datasets[0].borderWidth,
                                        hidden: false,
                                        index: i
                                    };
                                });
                            }
                            return [];
                        }
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    callbacks: {
                        label: function(context) {
                            const label = context.label || '';
                            const value = context.parsed;
                            return `${label}: ${value}%`;
                        }
                    }
                }
            },
            cutout: '60%',
            animation: {
                animateScale: true,
                animateRotate: true,
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 初始化销售业绩图
function initPerformanceChart() {
    const ctx = document.getElementById('performanceChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (reportsState.performanceChart) {
        reportsState.performanceChart.destroy();
    }
    
    // 销售人员数据
    const salespeople = ['张三', '李四', '王五', '赵六', '钱七', '孙八'];
    const targetData = [500000, 500000, 500000, 500000, 400000, 400000];
    const actualData = [620000, 540000, 480000, 420000, 430000, 380000];
    
    // 计算完成率
    const completionRates = actualData.map((actual, index) => 
        Math.round((actual / targetData[index]) * 100)
    );
    
    // 创建水平条形图
    reportsState.performanceChart = new Chart(ctx, {
        type: 'bar',
        data: {
            labels: salespeople,
            datasets: [
                {
                    label: '目标',
                    data: targetData,
                    backgroundColor: 'rgba(189, 195, 199, 0.3)',
                    borderColor: 'rgba(189, 195, 199, 1)',
                    borderWidth: 1,
                    order: 2
                },
                {
                    label: '实际',
                    data: actualData,
                    backgroundColor: 'rgba(46, 204, 113, 0.8)',
                    borderColor: 'rgba(46, 204, 113, 1)',
                    borderWidth: 1,
                    order: 1
                }
            ]
        },
        options: {
            indexAxis: 'y',
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    mode: 'index',
                    intersect: false,
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff',
                    callbacks: {
                        afterLabel: function(context) {
                            const index = context.dataIndex;
                            return `完成率: ${completionRates[index]}%`;
                        },
                        label: function(context) {
                            const label = context.dataset.label || '';
                            const value = context.parsed.x;
                            return `${label}: ${formatCurrency(value)}`;
                        }
                    }
                }
            },
            scales: {
                x: {
                    beginAtZero: true,
                    grid: {
                        color: 'rgba(0, 0, 0, 0.05)'
                    },
                    ticks: {
                        callback: function(value) {
                            return formatCurrency(value);
                        }
                    }
                },
                y: {
                    grid: {
                        display: false
                    }
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
    
    // 添加完成率标签
    renderCompletionLabels(salespeople, completionRates);
}

// 渲染完成率标签
function renderCompletionLabels(labels, rates) {
    const chartContainer = document.getElementById('performanceChart').closest('.chart-container');
    if (!chartContainer) return;
    
    // 检查是否已存在完成率容器，如存在则移除
    const existingLabels = chartContainer.querySelector('.completion-labels');
    if (existingLabels) {
        existingLabels.remove();
    }
    
    // 创建完成率标签容器
    const labelsContainer = document.createElement('div');
    labelsContainer.className = 'completion-labels';
    
    // 添加每个销售人员的完成率标签
    labels.forEach((label, index) => {
        const labelDiv = document.createElement('div');
        labelDiv.className = `completion-label ${rates[index] >= 100 ? 'exceeded' : rates[index] >= 80 ? 'achieved' : 'below'}`;
        
        // 计算位置
        const top = 30 + index * 50; // 估计位置，可能需要调整
        labelDiv.style.top = `${top}px`;
        labelDiv.style.right = '10px';
        
        labelDiv.textContent = `${rates[index]}%`;
        labelsContainer.appendChild(labelDiv);
    });
    
    // 添加到图表容器
    chartContainer.appendChild(labelsContainer);
}

// 初始化活动统计图表
function initActivityChart() {
    const ctx = document.getElementById('activityChart');
    if (!ctx) return;
    
    // 如果图表已经存在，先销毁
    if (reportsState.activityChart) {
        reportsState.activityChart.destroy();
    }
    
    // 活动类型数据
    const activities = ['电话', '邮件', '会议', '拜访', '演示', '其他'];
    
    // 根据时间范围获取数据
    let data;
    
    switch (reportsState.timeRange) {
        case 'month':
            data = [125, 85, 35, 25, 15, 10];
            break;
        case 'year':
            data = [1280, 960, 420, 320, 240, 180];
            break;
        case 'quarter':
        default:
            data = [380, 250, 100, 75, 45, 30];
            break;
    }
    
    // 创建雷达图
    reportsState.activityChart = new Chart(ctx, {
        type: 'radar',
        data: {
            labels: activities,
            datasets: [{
                label: '活动数量',
                data: data,
                backgroundColor: 'rgba(155, 89, 182, 0.2)',
                borderColor: 'rgba(155, 89, 182, 0.8)',
                borderWidth: 2,
                pointBackgroundColor: 'rgba(155, 89, 182, 1)',
                pointRadius: 4,
                pointHoverRadius: 6
            }]
        },
        options: {
            responsive: true,
            maintainAspectRatio: false,
            plugins: {
                legend: {
                    position: 'top',
                    labels: {
                        usePointStyle: true,
                        boxWidth: 6
                    }
                },
                tooltip: {
                    backgroundColor: 'rgba(0, 0, 0, 0.8)',
                    titleColor: '#fff',
                    bodyColor: '#fff'
                }
            },
            scales: {
                r: {
                    angleLines: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    },
                    grid: {
                        color: 'rgba(0, 0, 0, 0.1)'
                    },
                    pointLabels: {
                        color: 'rgba(0, 0, 0, 0.6)'
                    },
                    ticks: {
                        color: 'rgba(0, 0, 0, 0.4)',
                        backdropColor: 'transparent',
                        z: 100
                    }
                }
            },
            animation: {
                duration: 1000,
                easing: 'easeOutQuart'
            }
        }
    });
}

// 初始化报表筛选器
function initReportFilters() {
    // 初始化时间范围筛选
    const timeRangeSelect = document.getElementById('timeRangeSelect');
    if (timeRangeSelect) {
        timeRangeSelect.addEventListener('change', function() {
            reportsState.timeRange = this.value;
            updateReportCharts();
        });
    }
    
    // 初始化部门筛选
    const departmentSelect = document.getElementById('departmentFilter');
    if (departmentSelect) {
        departmentSelect.addEventListener('change', function() {
            reportsState.departmentFilter = this.value;
            updateReportCharts();
        });
    }
    
    // 初始化产品筛选
    const productSelect = document.getElementById('productFilter');
    if (productSelect) {
        productSelect.addEventListener('change', function() {
            reportsState.productFilter = this.value;
            updateReportCharts();
        });
    }
    
    // 初始化重置按钮
    const resetFiltersBtn = document.getElementById('resetFiltersBtn');
    if (resetFiltersBtn) {
        resetFiltersBtn.addEventListener('click', function() {
            // 重置筛选器
            if (timeRangeSelect) timeRangeSelect.value = 'quarter';
            if (departmentSelect) departmentSelect.value = 'all';
            if (productSelect) productSelect.value = 'all';
            
            // 重置状态
            reportsState.timeRange = 'quarter';
            reportsState.departmentFilter = 'all';
            reportsState.productFilter = 'all';
            
            // 更新图表
            updateReportCharts();
        });
    }
}

// 更新报表图表
function updateReportCharts() {
    initRevenueChart();
    initIndustryChart();
    initPerformanceChart();
    initActivityChart();
}

// 初始化报表导出功能
function initReportExport() {
    // 初始化导出按钮
    const exportBtn = document.getElementById('exportReportBtn');
    if (exportBtn) {
        exportBtn.addEventListener('click', function() {
            showNotification('报表导出功能已触发', 'info');
            
            // 这里只是模拟导出功能
            // 实际项目中，这里可以实现导出为PDF、Excel等功能
            setTimeout(() => {
                showNotification('报表导出成功', 'success');
            }, 1000);
        });
    }
    
    // 初始化打印按钮
    const printBtn = document.getElementById('printReportBtn');
    if (printBtn) {
        printBtn.addEventListener('click', function() {
            window.print();
        });
    }
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', initReports);